from __future__ import annotations

from datetime import datetime
from typing import List, Optional
import uuid

from pydantic import BaseModel, ConfigDict, Field, field_validator

from app.schemas.base import BaseSchema


class DictTypeBase(BaseModel):
    dict_name: str = Field(..., max_length=100, description="字典名称")
    dict_type: str = Field(..., max_length=100, description="字典类型标识")
    status: str = Field(default="0", description="状态（0 正常 1 停用）")
    remark: Optional[str] = Field(default=None, max_length=500, description="备注")

    @field_validator("dict_name")
    @classmethod
    def validate_dict_name(cls, value: str) -> str:
        if not value or not value.strip():
            raise ValueError("字典名称不能为空")
        return value.strip()

    @field_validator("dict_type")
    @classmethod
    def validate_dict_type(cls, value: str) -> str:
        if not value or not value.strip():
            raise ValueError("字典类型不能为空")
        return value.strip()

    @field_validator("status")
    @classmethod
    def validate_status(cls, value: str) -> str:
        if value not in {"0", "1"}:
            raise ValueError("状态只允许为 0 或 1")
        return value


class DictTypeCreate(DictTypeBase):
    pass


class DictTypeUpdate(BaseModel):
    dict_name: Optional[str] = Field(default=None, max_length=100)
    status: Optional[str] = Field(default=None)
    remark: Optional[str] = Field(default=None, max_length=500)

    @field_validator("dict_name")
    @classmethod
    def validate_dict_name(cls, value: Optional[str]) -> Optional[str]:
        if value is not None and not value.strip():
            raise ValueError("字典名称不能为空")
        return value.strip() if value else value

    @field_validator("status")
    @classmethod
    def validate_status(cls, value: Optional[str]) -> Optional[str]:
        if value is not None and value not in {"0", "1"}:
            raise ValueError("状态只允许为 0 或 1")
        return value


class DictTypeInDB(BaseSchema):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    dict_name: str
    dict_type: str
    status: str
    remark: Optional[str]
    create_by: Optional[str]
    update_by: Optional[str]
    created_at: datetime
    updated_at: datetime


class DictTypeListResponse(BaseModel):
    items: List[DictTypeInDB]
    total: int
    page: int
    page_size: int
    total_pages: int


class DictDataBase(BaseModel):
    dict_sort: int = Field(default=0, ge=0, description="排序")
    dict_label: str = Field(..., max_length=100, description="显示标签")
    dict_value: str = Field(..., max_length=100, description="键值")
    css_class: Optional[str] = Field(default=None, max_length=100)
    list_class: Optional[str] = Field(default=None, max_length=100)
    is_default: str = Field(default="N", description="是否默认 (Y/N)")
    status: str = Field(default="0", description="状态（0 正常 1 停用）")
    remark: Optional[str] = Field(default=None, max_length=500)

    @field_validator("dict_label")
    @classmethod
    def validate_dict_label(cls, value: str) -> str:
        if not value or not value.strip():
            raise ValueError("字典标签不能为空")
        return value.strip()

    @field_validator("dict_value")
    @classmethod
    def validate_dict_value(cls, value: str) -> str:
        if not value or not value.strip():
            raise ValueError("字典键值不能为空")
        return value.strip()

    @field_validator("is_default")
    @classmethod
    def validate_is_default(cls, value: str) -> str:
        value = value.upper()
        if value not in {"Y", "N"}:
            raise ValueError("是否默认只允许 Y 或 N")
        return value

    @field_validator("status")
    @classmethod
    def validate_status(cls, value: str) -> str:
        if value not in {"0", "1"}:
            raise ValueError("状态只允许为 0 或 1")
        return value


class DictDataCreate(DictDataBase):
    pass


class DictDataUpdate(BaseModel):
    dict_sort: Optional[int] = Field(default=None, ge=0)
    dict_label: Optional[str] = Field(default=None, max_length=100)
    dict_value: Optional[str] = Field(default=None, max_length=100)
    css_class: Optional[str] = Field(default=None, max_length=100)
    list_class: Optional[str] = Field(default=None, max_length=100)
    is_default: Optional[str] = Field(default=None)
    status: Optional[str] = Field(default=None)
    remark: Optional[str] = Field(default=None, max_length=500)

    @field_validator("dict_label")
    @classmethod
    def validate_dict_label(cls, value: Optional[str]) -> Optional[str]:
        if value is not None and not value.strip():
            raise ValueError("字典标签不能为空")
        return value.strip() if value else value

    @field_validator("dict_value")
    @classmethod
    def validate_dict_value(cls, value: Optional[str]) -> Optional[str]:
        if value is not None and not value.strip():
            raise ValueError("字典键值不能为空")
        return value.strip() if value else value

    @field_validator("is_default")
    @classmethod
    def validate_is_default(cls, value: Optional[str]) -> Optional[str]:
        if value is not None:
            value = value.upper()
            if value not in {"Y", "N"}:
                raise ValueError("是否默认只允许 Y 或 N")
        return value

    @field_validator("status")
    @classmethod
    def validate_status(cls, value: Optional[str]) -> Optional[str]:
        if value is not None and value not in {"0", "1"}:
            raise ValueError("状态只允许为 0 或 1")
        return value


class DictDataInDB(BaseSchema):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    dict_sort: int
    dict_label: str
    dict_value: str
    dict_type: str
    css_class: Optional[str]
    list_class: Optional[str]
    is_default: str
    status: str
    remark: Optional[str]
    create_by: Optional[str]
    update_by: Optional[str]
    created_at: datetime
    updated_at: datetime


class DictDataListResponse(BaseModel):
    items: List[DictDataInDB]
    total: int
    page: int
    page_size: int
    total_pages: int


class DictBatchRequest(BaseModel):
    types: List[str] = Field(..., min_length=1, description="需要查询的字典类型列表")

    @field_validator("types")
    @classmethod
    def validate_types(cls, value: List[str]) -> List[str]:
        cleaned = [item.strip() for item in value if item and item.strip()]
        if not cleaned:
            raise ValueError("字典类型列表不能为空")
        return cleaned


class DictBatchResponseItem(BaseModel):
    dict_type: str
    items: List[DictDataInDB]


class DictBatchResponse(BaseModel):
    items: List[DictBatchResponseItem]


class DictSortItem(BaseModel):
    id: uuid.UUID
    dict_sort: int = Field(..., ge=0)


class DictSortUpdateRequest(BaseModel):
    items: List[DictSortItem]

    @field_validator("items")
    @classmethod
    def validate_items(cls, value: List[DictSortItem]) -> List[DictSortItem]:
        if not value:
            raise ValueError("排序列表不能为空")
        return value
